import os
import shutil
import json
import platform
import sys
import subprocess
import glob
from driver import Initializer
from driver import Builder
from util import *
from option import Options

class Initializer_lua(Initializer):
    def __init__(self, options):
        self.options = options

    def check(self):
        if not os.path.exists("repo.init"):
            print("Base repo. uninitialized.")
            return False
        if not os.path.exists("repo.init.lua"):
            return self.init()
        else:
            return True

    def build_frontend(self):
        pass
        
    def build_backend(self):
        pass
        
    def init(self):
        os.chdir("tmp")
        if os.path.exists('rpc-backend-lua'):
            os.chdir("rpc-backend-lua")
            os.system("git pull")
            os.chdir('..')
        else:
            if os.system("git clone https://gitee.com/dennis-kk/rpc-backend-lua") != 0:
                print("git clone https://gitee.com/dennis-kk/rpc-backend-lua failed")
                return False
        shutil.copyfile("rpc-backend-lua/luagen.py", "../bin/luagen.py")
        os.chdir("..")
        open("repo.init.lua", "w").close()
        return True
        
    def checkEnv(self):
        os.system("protoc --version")
        os.system("git --version")
        os.system("cmake --version")
        if platform.system() == "Linux":
            if os.system("gcc --version") != 0:
                os.system("clang --version")
        else:
            print("Visual Studio 16 2019")

class Builder_lua(Builder):
    def __init__(self, options):
        Builder.__init__(self, options)

    def build_idl(self, name, sname = None):
        pass
        
    def addIdl2Repo(self, file_name, sname = None, add=True):
        if not add:
            file_name = "src/idl/" + file_name
        if not os.path.exists(file_name):
            print(file_name + " not found")
            return
        file_name = self.check_idl_name(file_name)
        if add:
            shutil.copyfile(file_name, "src/idl/" + os.path.basename(file_name))
        os.chdir("src/idl/")
        cmd = subprocess.Popen(["../../bin/rpc-frontend", "-f", os.path.basename(file_name)], stdout=subprocess.PIPE, stderr=subprocess.PIPE)
        ret = cmd.communicate()
        if cmd.returncode != 0:
            print(ret[1])
            return
        for file in glob.glob('*.cpp.json'):
            cmd = subprocess.Popen(["python", "../../bin/luagen.py", file, '--proxy-only'], stdout=subprocess.PIPE, stderr=subprocess.PIPE)
            cmd.communicate()
            if cmd.returncode != 0:
                print("luagen.py failed")
                print(ret[1])
                return
        (base_name, _) = os.path.splitext(os.path.basename(file_name))
        json_str = json.load(open(base_name + ".idl.cpp.json"))
        for service in json_str["services"]:
            if sname is not None:
                if sname != service['name']:
                    continue
            is_lua = False
            if not service.has_key("notations"):
                continue
            for notation in service["notations"]:
                if notation.has_key("script_type"):
                    for script_type in notation["script_type"]:
                        if script_type == "lua":
                            is_lua = True
            if not is_lua:
                continue
            cmd = subprocess.Popen(["python", "../../bin/luagen.py", base_name + ".idl.cpp.json"], stdout=subprocess.PIPE, stderr=subprocess.PIPE)
            cmd.communicate()
            if cmd.returncode != 0:
                print("luagen.py failed for "+base_name + ".idl.cpp.json")
                print(ret[1])
                return
            if not os.path.exists("../../usr/lua/" + service['uuid'] + "_lua/stub"):
                os.makedirs("../../usr/lua/" + service['uuid'] + "_lua/stub")
            if not os.path.exists("../../usr/lua/" + service['uuid'] + "_lua/script"):
                os.makedirs("../../usr/lua/" + service['uuid'] + "_lua/script")
            if not os.path.exists("../../usr/lua/lua_proxy"):
                os.makedirs("../../usr/lua/lua_proxy")
            if not os.path.exists("../../usr/lua/proto"):
                os.makedirs("../../usr/lua/proto")
            if not os.path.exists("../../usr/lua/json"):
                os.makedirs("../../usr/lua/json")
            if not os.path.exists("../../usr/lua/" + service['uuid'] + "_lua/script/main.lua"):
                shutil.copyfile(service['uuid'] + "_lua/script/main.lua", "../../usr/lua/" + service['uuid'] + "_lua/script/main.lua")
            shutil.copyfile(service['uuid'] + "_lua/stub/stub.lua", "../../usr/lua/" + service['uuid'] + "_lua/stub/stub.lua")
            for file in glob.glob("lua_proxy/*.lua"):
                shutil.copy(file, "../../usr/lua/lua_proxy")
            for file in glob.glob("*.cpp.json"):
                shutil.copy(file, "../../usr/lua/json")
            for file in glob.glob("*.proto"):
                shutil.copy(file, "../../usr/lua/proto")
        os.chdir("../../")
        
    def updateRoot(self):
        initializer = Initializer_lua(Options())
        os.chdir("tmp/rpc-frontend/")
        os.system("git pull")
        os.chdir("..")
        initializer.build_frontend()
        os.chdir("..")
        os.chdir("tmp/rpc-backend-lua/")
        os.system("git pull")
        shutil.copyfile("luagen.py", "../../bin/luagen.py")
        os.chdir("..")
        initializer.build_backend()
        os.chdir("../../")